package com.sprouting.ops.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sprouting.ops.dao.*;
import com.sprouting.ops.interfaces.ConstantBase;
import com.sprouting.ops.model.DromaraFileStorage;
import com.sprouting.ops.model.OpsStakeholder;
import com.sprouting.ops.model.OpsSysDict;
import com.sprouting.ops.model.qo.OpsStakeholderQo;
import com.sprouting.ops.model.vo.EnvAccountVo;
import com.sprouting.ops.model.vo.OpsStakeholderVo;
import com.sprouting.ops.utils.EntityTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 干系人(OpsStakeholder)(OPS_STAKEHOLDER) 表服务实现类
 *
 * @author ：lx（长沙麓谷）
 * @date 创建时间：2025-09-01 16:53:16
 */
@Service
@Slf4j
public class OpsStakeholderService extends ServiceImpl<OpsStakeholderDao, OpsStakeholder> {

    @Resource
    private OpsStakeholderDao opsStakeholderDao;
    @Resource
    private OpsSysDictDao opsSysDictDao;
    @Resource
    private DromaraFileStorageDao dromaraFileStorageDao;


    /**
     * 分页查询 干系人
     * @param page 分页参数
     * @param query 查询参数
     * @return
     */
    public Page<OpsStakeholderVo> getListPage(Page page, OpsStakeholderQo query){
        Page<OpsStakeholderVo> listPage = opsStakeholderDao.getListPage(page, query);
        List<OpsStakeholderVo> records = listPage.getRecords();
        if (CollUtil.isEmpty(records)){
            return listPage;
        }

        // 找到要查询字典的
        List<String> dictIdList = new ArrayList<>();
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getLevel, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getStakeholderType, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getProjectRole, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getBenefitClass, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getInfluenceField, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getRightLevel, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getInterestLevel, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getInterestQuadrant, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getInteractTarget, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getInteractFrequency, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getInteractFormat, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getDependentOneself, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getDependentProject, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getDecisionStyle, dictIdList);
        EntityTool.addNonEmptyFieldValues(records, OpsStakeholderVo::getMotivation, dictIdList);

        // 字典id -> 字典
        Map<String, OpsSysDict> map = new HashMap<>();
        if (CollUtil.isNotEmpty(dictIdList)){
            List<OpsSysDict> list = opsSysDictDao.getByIdList(dictIdList);
            Map<String, OpsSysDict> stakeholderMap = EntityTool.toMap(list, OpsSysDict::getId);
            map.putAll(stakeholderMap);
        }

        for (OpsStakeholderVo record : records) {
            // 转换性别
            if (ConstantBase.Sex.MEN.equals(record.getSex())){
                record.setSexCh("男");
            } else if (ConstantBase.Sex.WOMEN.equals(record.getSex())){
                record.setSexCh("女");
            } else {
                record.setSexCh("未知");
            }

            // 添加字典信息
            record.setLevelCh(getDictNameSafe(map, record.getLevel(), ""));
            record.setStakeholderTypeCh(getDictNameSafe(map, record.getStakeholderType(), ""));
            record.setStakeholderTypeCh(getDictNameSafe(map, record.getStakeholderType(), ""));
            record.setProjectRoleCh(getDictNameSafe(map, record.getProjectRole(), ""));
            record.setBenefitClassCh(getDictNameSafe(map, record.getBenefitClass(), ""));
            record.setInfluenceFieldCh(getDictNameSafe(map, record.getInfluenceField(), ""));
            record.setInterestQuadrantCh(getDictNameSafe(map, record.getInterestQuadrant(), ""));
            record.setInteractTargetCh(getDictNameSafe(map, record.getInteractTarget(), ""));
            record.setInteractFrequencyCh(getDictNameSafe(map, record.getInteractFrequency(), ""));
            record.setInteractFormatCh(getDictNameSafe(map, record.getInteractFormat(), ""));
            record.setDependentOneselfCh(getDictNameSafe(map, record.getDependentOneself(), ""));
            record.setDependentProjectCh(getDictNameSafe(map, record.getDependentProject(), ""));
            record.setDecisionStyleCh(getDictNameSafe(map, record.getDecisionStyle(), ""));
            record.setMotivationCh(getDictNameSafe(map, record.getMotivation(), ""));
        }

        return listPage;
    }

    /**
     * 安全获取字典名称
     * @param dictMap 字典映射表
     * @param id 字典编码
     * @param defaultName 默认名称
     * @return 字典名称或默认值
     */
    private String getDictNameSafe(Map<String, OpsSysDict> dictMap, String id, String defaultName) {
        if (StrUtil.isEmpty(id) || dictMap == null) {
            return defaultName;
        }
        OpsSysDict dict = dictMap.get(id);
        return dict != null && dict.getName() != null ? dict.getName() : defaultName;
    }

    /**
     * 保存干系人
     * @param bo 干系人
     * @param icoFile 干系人头像
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOpsStakeholder(OpsStakeholder bo, DromaraFileStorage icoFile) {
        opsStakeholderDao.insert(bo);
        if (icoFile != null){
            dromaraFileStorageDao.updateById(icoFile);
        }
    }

    /**
     * 更新干系人
     * @param bo 干系人
     * @param unifiedFileInfo 干系人头像
     */
    @Transactional(rollbackFor = Exception.class)
    public void updOpsStakeholder(OpsStakeholder bo, DromaraFileStorage[] unifiedFileInfo) {
        opsStakeholderDao.updateById(bo);
        if (unifiedFileInfo[0] != null){
            // 新的
            dromaraFileStorageDao.updateById(unifiedFileInfo[0]);
        }
        if (unifiedFileInfo[1] != null){
            // 旧的文件
            dromaraFileStorageDao.updateById(unifiedFileInfo[1]);
        }
    }

    /**
     * 删除干系人
     * @param id 干系人
     * @param unifiedFileInfo 图标
     */
    @Transactional(rollbackFor = Exception.class)
    public void delOpsStakeholder(String id, DromaraFileStorage unifiedFileInfo) {
        opsStakeholderDao.deleteById(id);
        // 删除图标
        if (unifiedFileInfo != null){
            dromaraFileStorageDao.updateById(unifiedFileInfo);
        }
    }


}
